/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bsc.war.handler;

import bsc.ejb.entity.Attachment;
import bsc.ejb.entity.ColorimetrySettings;
import bsc.ejb.entity.Milestone;
import bsc.ejb.entity.Note;
import bsc.ejb.entity.MilestoneTracer;
import bsc.ejb.entity.Project;
import bsc.ejb.entity.Task;
import bsc.ejb.entity.Tracer;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.ActionPlanPojo;
import bsc.war.model.MilestoneProgressPojo;
import bsc.war.model.TracerPojo;
import bsc.war.service.ScoreCardUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author luisZavaleta
 */
public class DashboardProject extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        //Create MoodelandView
        ModelAndView mv = new ModelAndView("dashboardProject");
        try {

            //Delegate
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            //Find the scorecards
            Long idScoreCard = Long.parseLong(request.getParameter("scoreCard"));
            Project project = delegate.findProject(idScoreCard);
            Map<Note, List<Attachment>> noteAttachments = new HashMap<Note, List<Attachment>>();

            //Get the tracers (Budget - Progress) of the project
            List<Tracer> tracersProject = delegate.findTracer(project);

            //Create the tracersPojo with the information about Tracers.
            List<TracerPojo> tracersPojo = new ArrayList<TracerPojo>();

            Tracer tracerBudget = null;
            Tracer tracerProgress = null;

            //Fill the tracerPojo with the info.
            for (Tracer tracer : tracersProject) {
                TracerPojo tracerPojo = new TracerPojo();
                tracerPojo.setName(tracer.getName());
                tracerPojo.setWeight(tracer.getPercentFactor());
                if (tracer.getType() == Tracer.Type.PROGRESS) {
                    tracerPojo.setScore(ScoreCardUtils.calculateProgressScore(delegate, project, tracer));
                    tracerProgress = tracer;
                } else if (tracer.getType() == Tracer.Type.BUDGET) {
                    tracerPojo.setScore(ScoreCardUtils.calculateBudgetScore(delegate, project, tracer));
                    tracerBudget = tracer;
                }
                tracersPojo.add(tracerPojo);
            }

            //Se agrega el tracer TOTAL

            TracerPojo tracerPojo = new TracerPojo();
            tracerPojo.setName("Total");
            tracerPojo.setWeight(1D);
            tracerPojo.setScore(ScoreCardUtils.calculateScore(delegate, project).getScore());

            tracersPojo.add(tracerPojo);

            //Get the milestones of the project in order to calculate the budget
            List<Milestone> milestones = delegate.findMilestone(project);

            //Create the list of MileStoneProgressPojo to save the budget information of each milestone
            List<MilestoneProgressPojo> lmpp = new ArrayList<MilestoneProgressPojo>();

            // Total Real and Goal of the budget
            Double totalRealBudget = 0D;
            Double totalGoalBudget = 0D;

            //Fill the information of each milestone
            for (Milestone milestone : milestones) {
                MilestoneTracer milestoneTracerBudget = delegate.findMilestoneTracer(milestone, tracerBudget);

                MilestoneProgressPojo mpp = new MilestoneProgressPojo();
                mpp.setName(milestone.getName());

                //Accum the reals value
                Double real = milestoneTracerBudget.getRealValue();
                totalRealBudget += real == null ? 0.0D : real;

                //Accum the target value
                Double goal = milestoneTracerBudget.getGoalValue();
                totalGoalBudget += goal == null ? 0.0D : goal;

                mpp.setReal(real);
                mpp.setGoal(goal);
                mpp.setScore(ScoreCardUtils.calculateBudgetScoreMilestone(delegate, milestoneTracerBudget));

                //Progress Attributes
                MilestoneTracer milestoneTracerProgress = delegate.findMilestoneTracer(milestone, tracerProgress);

                Double realProgress = milestoneTracerProgress.getRealValue();
                Double goalProgress = ScoreCardUtils.getProgressGoal(milestone);
                Double scoreProgress = ScoreCardUtils.calculateMilestoneProgressScore(delegate, milestone, tracerProgress);

                mpp.setRealProgress(realProgress);
                mpp.setGoalProgress(goalProgress);
                mpp.setScoreProgress(scoreProgress.isNaN() ? null : scoreProgress);

                lmpp.add(mpp);
            }

            //Create the Total of all milestones
            MilestoneProgressPojo mpp = new MilestoneProgressPojo();

            mpp.setName("Total");
            mpp.setReal(totalRealBudget);
            mpp.setGoal(totalGoalBudget);
            mpp.setScore(ScoreCardUtils.calculateBudgetScore(delegate, project, tracerBudget));

            int totalDays = ScoreCardUtils.getWorkingDays(delegate, project);

            Task principalTask = delegate.findRootTask(project);

            mpp.setRealProgress(ScoreCardUtils.getRealProgress(delegate, totalDays, principalTask, tracerProgress));
            mpp.setGoalProgress(ScoreCardUtils.getGoalProgress(delegate, totalDays, principalTask, tracerProgress));

            Double scoreProgress = ScoreCardUtils.calculateProgressScore(delegate, project, tracerProgress);
            mpp.setScoreProgress(scoreProgress.isNaN() ? null : scoreProgress);

            //System.out.println("El Score Pogress es: "+ mpp.getScoreProgress());

            lmpp.add(mpp);

            //Get the notes of the project
            List<Note> notes = delegate.findNote(project);
            for (Note note : notes) {
                List<Attachment> attachments = delegate.findAttachment(note);
                noteAttachments.put(note, attachments);
            }
            request.setAttribute("notes", notes);
            request.setAttribute("noteAttachments", noteAttachments);



            List<ColorimetrySettings> colorimetries = delegate.findColorimetrySettings(project);
            Map<ColorimetrySettings, Double> colorRangeMin = new HashMap<ColorimetrySettings, Double>();
            Map<ColorimetrySettings, Double> colorRangeMax = new HashMap<ColorimetrySettings, Double>();
            for (ColorimetrySettings colorimetrySettings : colorimetries) {
                Double maxScore = colorimetrySettings.getMaxScore();
                Double minScore = colorimetrySettings.getMinScore();

                colorRangeMax.put(colorimetrySettings, maxScore);
                colorRangeMin.put(colorimetrySettings, minScore);
            }

            //ActionPlans
            List<ActionPlanPojo> actionPlanPojos = ScoreCardUtils.getActionPlans(delegate, project);
            request.setAttribute("actionPlanPojos", actionPlanPojos);

            //Colores
            request.setAttribute("colorimetries", colorimetries);
            request.setAttribute("colorRangeMin", colorRangeMin);
            request.setAttribute("colorRangeMax", colorRangeMax);


            mv.addObject("tracers", tracersPojo);
            mv.addObject("milestones", lmpp);
            mv.addObject("project", project);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }
}
